package com.example.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bo.RedisUserInfo;
import com.example.dto.CmsUserRegisterDto;
import com.example.utils.RedisUtil;
import com.example.domain.CmsUser;
import com.example.dto.CmsLogin;
import com.example.mapper.CmsUserMapper;
import com.example.service.ICmsUserService;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author zhengyue
 * @since 2020-03-13
 */
@Service
@Slf4j
public class CmsUserServiceImpl extends ServiceImpl<CmsUserMapper, CmsUser> implements ICmsUserService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private CmsUserMapper cmsUserMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Value("${jwt.config.tokenHead}")
    private String tokenHead;
    @Value("${jwt.config.expiration}")
    private Long expiration;

    @Override
    public RedisUserInfo login(CmsLogin cmsLogin) {
        String token = null;
        RedisUserInfo redisUserInfo = new RedisUserInfo();
        //根据用户名username加载userDetails
        UserDetails userDetails = userDetailsService.loadUserByUsername(cmsLogin.getNumber());
        if(!passwordEncoder.matches(cmsLogin.getPassword(), userDetails.getPassword())){
            throw new BadCredentialsException("密码错误");
        }
        //根据userDetails构建新的Authentication
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //存放authentication到SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        token = jwtUtils.create(userDetails);

        redisUserInfo.setStaffNumber(cmsLogin.getNumber());
        //用户信息
        CmsUser cmsUser = cmsUserMapper.selectOne(new QueryWrapper<CmsUser>().lambda()
                .eq(CmsUser::getNumber, cmsLogin.getNumber()));
        redisUserInfo
            .setId(cmsUser.getId())
            .setStaffNumber(cmsUser.getNumber())
            .setPermissionList(null)
            .setToken(tokenHead + token);
        redisUtil.set(cmsLogin.getNumber(), JSONUtil.toJsonStr(redisUserInfo));
        redisUtil.expire(cmsLogin.getNumber(), expiration);
        return redisUserInfo;
    }


    @Override
    public Boolean register(CmsUserRegisterDto registerDto) {
        if(StringUtils.isEmpty(registerDto.getPassword())) {
            registerDto.setPassword("000000");
        }
        CmsUser aminInfo = cmsUserMapper.selectOne(new QueryWrapper<CmsUser>().lambda()
                .eq(CmsUser::getNumber, registerDto.getNumber()));
        if(!ObjectUtil.isNotNull(aminInfo)) {
            CmsUser cmsUser = new CmsUser();
            BeanUtils.copyProperties(registerDto, cmsUser);

            cmsUser.setPassword(passwordEncoder.encode(cmsUser.getPassword()));
            //默认头像地址
            cmsUser.setImage("");
            int insert = cmsUserMapper.insert(cmsUser);
            return insert == 1 ? true : false;
        }
        return false;
    }
}
